package me.leon.aop

import android.util.Log
import android.view.View
import me.leon.aop.ClickUtils.isFastDoubleClick
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.aspectj.lang.reflect.MethodSignature

/**
 * <p>description：</p>
 * <p>author：Leon</p>
 * <p>date：2019/8/29 0029</p>
 * <p>e-mail：deadogone@gmail.com</p>
 *
 */
@Aspect
class LeonAop2 {
    @Pointcut("execution(@me.leon.aop.SingleClickKotlin * *(..))")
    fun click() {
    }

    @Around("click()")
    fun clickHandle(joinPoint: ProceedingJoinPoint) {
        var view: View? = null
        for (arg in joinPoint.args) {
            if (arg is View) {
                view = arg
                break
            }
        }
        if (view == null) {
            return
        }

        val methodSignature = joinPoint.signature as MethodSignature
        val method = methodSignature.method
        if (!method.isAnnotationPresent(SingleClickKotlin::class.java)) {
            return
        }
        val singleClick = method.getAnnotation(SingleClickKotlin::class.java)
        // 判断是否快速点击
        if (!isFastDoubleClick(view, singleClick.value.toLong())) {
            // 不是快速点击，执行原方法
            joinPoint.proceed()
        } else {
            Log.d("AOP Kt", "快速 click 过滤 : " + joinPoint.getSignature().getName())
            return
        }
        Log.d("AOP Kt", "click : " + joinPoint.getSignature().getName())

    }

    @Pointcut("execution(@me.leon.aop.TimeTakes * *(..))")
    fun timeTake() {
    }

    @Around("timeTake()")
    fun timeCountHandle(joinPoint: ProceedingJoinPoint) {
        val methodSignature = joinPoint.signature as MethodSignature
        val method = methodSignature.method
        if (!method.isAnnotationPresent(TimeTakes::class.java)) {
            return
        }
        val singleClick = method.getAnnotation(TimeTakes::class.java)
        Log.d("AOP Kt",  " TimeTakes tag  " + singleClick.value)
        val time = System.currentTimeMillis()
        joinPoint.proceed()
        Log.d("AOP Kt", joinPoint.getSignature().getName() + "  takes time: "
                + (System.currentTimeMillis() - time))

    }
}